# marshmallow映射文件
from marshmallow import fields
from marshmallow_sqlalchemy import ModelSchema

from application import db
from application.users.models import Users, Permission, Role, RolePermission, UsersRole


class UsersRoleSchema(db.Model):

    class Meta(ModelSchema.Meta):
        model = UsersRole
        sqla_session = db.session

    user_id = fields.Integer()
    role_id = fields.Integer


class RolePermissionSchema(db.Model):

    class Meta(ModelSchema.Meta):
        model = RolePermission
        sqla_session = db.session

    role_id = fields.Integer()
    permission_id = fields.Integer()


class PermissionSchema(db.Model):
    # 映射Permission到marshmallow
    class Meta(ModelSchema.Meta):
        model = Permission
        sqla_session = db.session

    id = fields.Integer(dump_only=True)
    name = fields.String(required=True, error_messages={'required': '用名必填'})
    code = fields.String(required=True, error_messages={'required': '用名必填'})


class RoleSchema(db.Model):
    # 映射role到marshmallow
    class Meta(ModelSchema.Meta):
        model = Role
        sqla_session = db.session

    id = fields.Integer(dump_only=True)
    name = fields.String(required=True, error_messages={'required': '用名必填'})
    code = fields.String(required=True, error_messages={'required': '用名必填'})
    permission = fields.Nested(PermissionSchema)


class UsersSchema(ModelSchema):
    # 映射Users到marshmallow
    class Meta(ModelSchema.Meta):
        model = Users
        sqla_session = db.session

    # dump_only只允许从接口读出该数据(只允许从model序列化为字典,不允许从接口反序列化到model)
    id = fields.Integer(dump_only=True)
    username = fields.String(required=True, error_messages={'required': '用名必填'})
    # load_only只允许接口写入这个数据(只允许字典反序列化为model,不允许model序列化到接口)
    password = fields.String(load_only=True)
    fullname = fields.String(required=True, error_messages={'required': '姓名必填'})
    status = fields.Integer()
    created_time = fields.DateTime(dump_only=True)
    # 当前听课状态
    current_listen_status = fields.String()
    # 头像
    avatar = fields.String(dump_only=True)
    role = fields.Nested(RoleSchema)








